<!--tvm票款差异协查-->
<template>
  <div class="TvmTicketCYXC el-card is-always-shadow el-card__body">
    <avue-crud
      ref="TvmTicketCYXC"
      :option="option"
      :table-loading="listLoading"
      :data="data"
      :page.sync="page"
      :search.sync="searchForm"
      @search-change="handleFilter"
      @selection-change="selectionChange"
      @refresh-change="refreshChange"
      @on-load="refreshChange"
      :row-style="rowStyle"
      :cell-style="cellStyle">
      <template slot="menuRight">
        <el-button type="primary" v-if="permissionList.sendStatus" size="mini" @click="sendStatus('3')">下发设备部和车站协查</el-button>
	<el-button type="primary" v-if="permissionList.sendStatus" size="mini" @click="sendStatus('1')">下发设备部协查</el-button>
	<el-button type="primary" v-if="permissionList.sendStatus" size="mini" @click="sendStatus('2')">下发车站协查</el-button>

        <el-button type="primary" v-if="permissionList.replaceContent" size="mini" @click="replaceContent()">一键替换</el-button>
	<el-button type="primary"  size="mini" @click="delBatchs">删除</el-button>
       
<!--        <el-button type="primary"  size="mini" @click="exportData">导出</el-button>-->
        
      </template>
      <template slot-scope="scope" slot="lineCodeSearch">
        <el-select v-model="searchForm.lineCode" placeholder="请选择" style="width: 150px" clearable @change="changeLine" filterable>
          <el-option
            v-for="(item,index) in lineCodes"
            :key="index"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </template>
      <template slot-scope="scope" slot="stationCodeSearch">
        <el-select v-model="searchForm.stationCode" placeholder="请选择" style="width: 150px" @change="changeStation" filterable>
          <el-option
            v-for="(item,index) in stationCodes"
            :key="index"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </template>
      <template slot-scope="scope" slot="settleTimeSearch">
        <el-date-picker
          v-model="searchForm.settleTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="收入日期">
        </el-date-picker>
      </template>
      <template slot-scope="scope" slot="tvmOrderSearch">
        <el-select v-model="searchForm.tvmOrder" placeholder="请选择" style="width: 150px" filterable >
          <el-option
            v-for="(item,index) in tvmCodes"
            :key="index"
            :label="item.tvmCode"
            :value="item.tvmCode">
          </el-option>
        </el-select>
      </template>
      <template slot="searchMenu" slot-scope="{row,size}">
        <el-button :size="size" @click="()=>{setSearchFiledsEmpty(row);setSearchFiledsEmpty(searchForm);getList()}" icon="el-icon-delete">清空</el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button v-if="(scope.row.assistInvestStatus=='8'|| scope.row.jdReplyStatus == 1) && scope.row.replaceStatus == 0 && scope.row.assistCategory!=0" type="text" size="small" plain @click.stop="previewEditor(scope.row)">回馈预览</el-button>
        <el-button v-if="!((scope.row.assistInvestStatus=='8'|| scope.row.jdReplyStatus == 1) && scope.row.replaceStatus == 0 && scope.row.assistCategory!='0')" type="text" size="small" plain @click.stop="previewEditor(scope.row)">预览</el-button>
      </template>
    </avue-crud>
    <HuikuiInfo ref="HuikuiInfo" v-if="isShowDia"></HuikuiInfo>
</div>
</template>


<script>
    import {getForm, postForm} from '@/api/gen/gen'
    import ExportJsonExcel from "js-export-excel";
    import HuikuiInfo from './HuikuiInfo';
    import {
      getTvmTicketCYXCList, sendStatusTvmTicketCYXC,
      updateSwAuTvmBoxAmountDifference,delBatch
    } from "../../../../../api/subwayRat/TVMRevenueVarianceAudit.TvmChaYiDXC/TvmTicketCYXC";
    import {
      getgetStationCodes,
      getLineCodes, getLineName, getQianxiangType, getRepalceStatus, getStationName,
      getXieChaStatusFormat, replayStatus,repalceStatus,
      xieChaStatus, setSearchFiledsEmpty, clearSelect, getLineAndStationByCode, getSwPmTvmCodeList, fenExYuangettoFixed2,assistCategoryData,getAssistCategory
    } from '../../../../../api/subwayRat/commonCheck';
    import {exportDataToExcel} from "../../../../../api/subwayRat/exportSelf";
    import transitUtil from "../../../../../api/subwayRat/transitUtil";
    import {mapGetters} from "vuex";
    export default {
      components:{
        HuikuiInfo,
      getLineCodes
      },
      data() {
            return {
              lineCodes:[],
              stationCodes:[],
              tvmCodes:[],
              selectKeys:[], //存放对像
              selectKeyVals:[], //存放值
              isShowDia:false,
              listLoading: true,
              searchForm:{
                lineCode:'9',
                stationCode:''
              },
              data: [],
              page: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 20, // 每页显示多少条,
                isAsc: false// 是否倒序
              },
              option:{},
            }
        },
      computed: {
        ...mapGetters(["permissions"]),
        permissionList () {
          return {
            replaceContent: this.vaildData(
              this.permissions.tvm_ticket_one_click_replacement,
              false
            ),
            sendStatus: this.vaildData(
              this.permissions.tvm_ticket_issue_assistance,
              false
            ),
          };
        },
      },
        created() {
          this.changeLine("9")
          this.option=this.getOption();
        },
        methods: {
          refreshChange() {
            this.getList()
          },
          cellStyle({ row, column, rowIndex,columnIndex }) {
            if(7==columnIndex){
              if (row.diffMoney < 0) {
                return {
                  color: "red",
                };
              }else if (row.diffMoney > 0) {
                return {
                  color: "green",
                };
              }
            }
          },
          rowStyle({ row, column, rowIndex }) {
            // if (row.diffMoney != 0) {
            //   return {
            //     backgroundColor: "#eee",
            //     color: "red",
            //   };
            // }
          },
          setSearchFiledsEmpty,
          getList() {
            this.listLoading = true;
            Object.assign(this.searchForm,this.page);
	    this.searchForm.assistCategoryRole='audit';//查询下发协查类型
            getTvmTicketCYXCList(this.searchForm).then((response)=>{
              this.data = response.data.data;
              this.listLoading = false;
              this.page.total=response.data.total;
            });
          },
          selectionChange(list){
            this.selectKeys=list;
            this.selectKeyVals=[];
            for(let i=0;i<list.length;i++){
              this.selectKeyVals.push(list[i].id);
            }
          },
          handleFilter(params, done) {
            Object.assign(this.searchForm,params);
            this.getList()
            done()
          },
          replaceContent(){
            /*
	    if(this.selectKeys.length<=0){
              this.$message.info("请选择已协查数据操作！");
              return;
            }
            if (!this.isassistInvestStatus()) {
              this.$message.info("请选择部门审核通过且机电已回馈的数据！");
              return;
            }*/
	    if(this.selectKeys.length<=0 || this.isAssistCategoryStatus()==false || this.isassistInvestStatus()==false|| this.isreplaceStatus()==false){
              this.$message.info("请选择协查含有机电部并且涉及部门已审核通过的并且未替换的数据！");
              return;
            }
            let ids=[];
            for(let i=0;i<this.selectKeys.length;i++){
              if(this.selectKeys[i].replaceStatus==0){
                ids.push(this.selectKeys[i].id);
              }
            }
            if(ids.length==0){
              this.$message.warning("无有效替换数据！");
              return;
            }
            this.$confirm('确定一键替换?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              updateSwAuTvmBoxAmountDifference({ids:ids.join(",")}).then(res=>{
                if(res.data.code==0){
                  this.$message.success("操作成功！");
                  this.getList();
                  clearSelect(this.$refs.TvmTicketCYXC)
                }else{
                  this.$message.error("操作失败！");
                }
              });
            }).catch(() => {

            });
          },
           //下发协查（分三个按钮）
	  async sendStatus(assistCategory){
            if(this.selectKeys.length<=0){
              this.$message.warning("请选择下发数据！");
              return;
            }
            let isSecondStation = 0;
	    let isSecondDevice = 0;
	   for (let i = 0; i < this.selectKeys.length; i++) {
	           let oldCategory = this.selectKeys[i].assistCategory;
		    if (oldCategory == 3) {
		      this.$message.warning("请选择未下发数据！");
		      return;
		    }
		    if (oldCategory == 1 && assistCategory == 1) {
		      this.$message.warning("选中的数据中存在之前已下发过设备部，不能再下发！");
		      return;
		    }
		    if (oldCategory == 1 && assistCategory == 3) {
		      this.$message.warning("选中的数据中存在之前已下发过设备部，不能再下发！");
		      return;
		    }
		    if (oldCategory == 2 && assistCategory == 2) {
		      this.$message.warning("选中的数据中存在之前已下发过车站，不能再下发！");
		      return;
		    }
		    if (oldCategory == 2 && assistCategory == 3) {
		      this.$message.warning("选中的数据中存在之前已下发过车站，不能再下发！");
		      return;
		    }
		   
		    // 标记二次下发情况
		    if (oldCategory == 1 && assistCategory == 2) {
		      isSecondStation = 1;
		    }
		    if (oldCategory == 2 && assistCategory == 1) {
		      isSecondDevice = 1;
		    }
	    }
	    // 添加二次下发确认逻辑
	  if (isSecondStation || isSecondDevice) {
	    let confirmMessage = '';
	    let confirmTitle = '二次下发确认';

	    if (isSecondStation && assistCategory == 2) {
	      confirmMessage = '选中的数据中存在之前已经下发过设备部，再次下发给车站吗？';
	    } else if (isSecondDevice && assistCategory == 1) {
	      confirmMessage = '选中的数据中存在之前已经下发过车站，再次下发给设备部吗？';
	    }

	    this.$confirm(confirmMessage, confirmTitle, {
	      confirmButtonText: '确定',
	      cancelButtonText: '取消',
	      type: 'warning'
	    }).then(() => {
	      // 用户确认后执行下发
	      this.executeSend(assistCategory);
	    }).catch(() => {
	      // 用户取消不做任何操作
	    });
	  } else {
	    // 正常下发时使用更合适的提示
	    let confirmMessage = '确定要下发选中的数据吗？';
	    let confirmTitle = '下发确认';

	    this.$confirm(confirmMessage, confirmTitle, {
	      confirmButtonText: '确定',
	      cancelButtonText: '取消',
	      type: 'info'
	    }).then(() => {
	      this.executeSend(assistCategory);
	    }).catch(() => {
	      // 用户取消不做任何操作
	    });
	  }
           
         },
	  // 封装发送方法
	async executeSend(assistCategory) {
	  let messageLSList = [];
            for(let i=0;i<this.selectKeys.length;i++){
              let data = await getLineAndStationByCode({"lineCode":this.selectKeys[i].lineCode, "code":this.selectKeys[i].stationCode});
              messageLSList.push({
                "content":"站点：" + data.data[0].name + ",差异金额：" + (this.selectKeys[i].diffMoney/100).toFixed(2),
                "lineCode":this.selectKeys[i].lineCode,
                "stationCode":this.selectKeys[i].stationCode
              })
            }

	  let p = {
	    messageLSList: JSON.stringify(messageLSList),
	    title: this.$store.getters.tag.label,
	    msgType: "下发",
	    ids: this.selectKeyVals.join(','),
	    assistCategory: assistCategory,
	    ...(assistCategory === '1' && { jdType: "TvmTicketCYSC_001" }),
	    ...(assistCategory === '2' && { kyType: "TvmTicketCYSC_002" }),
	    ...(assistCategory === '3' && {
	      jdType: "TvmTicketCYSC_001",
	      kyType: "TvmTicketCYSC_002"
	    })
	  };

	  sendStatusTvmTicketCYXC(p).then(res=>{
	    if (res.data.code == 0) {
	      this.$message.success("操作成功！");
	      this.getList();
	    } else {
	      this.$message.error("操作失败！");
	    }
	  });
	} ,
          changeLine(v){ //改变线路时
            getgetStationCodes(v).then(res=>{
              this.stationCodes=res;
              this.searchForm.stationCode='';
            });
            this.searchForm.stationCode='';
          },
          changeStation(v){ //改变站点
            let param={};
            param.lineCode=this.searchForm.lineCode;
            param.stationCode=v;
            getSwPmTvmCodeList(param).then(r=>{
              this.tvmCodes=r.data;
            });
          },
          isassistInvestStatus(){ // 是否协查
            for(let i=0;i<this.selectKeys.length;i++){
              let row=this.selectKeys[i];
	      if(row.assistCategory=='2'||row.assistCategory=='3'){
	          if(row.assistInvestStatus!=8){
                      return false
                  }
	      }              
              if (row.jdReplyStatus==0) {
                return false
              }
              if (row.replaceStatus==1) {
                return false
              }
            }
            return true;
          },
	  isAssistCategoryStatus(){ // 是否含有发机电的协查
            for(let i=0;i<this.selectKeys.length;i++){
              let row=this.selectKeys[i];
              if(row.assistCategory!='1' &&row.assistCategory!='3'){
                return false
              }
            }
            return true;
          },
	  isreplaceStatus(){ // 是否替换
            for(let i=0;i<this.selectKeys.length;i++){
              let row=this.selectKeys[i];
              if(row.replaceStatus==1){
                return false
              }
            }
            return true;
          },
          async getLineName(query){
            let re="";
             await getLine(query).then(async res=>{
               re=await res.data.name;
            });
            return re;
          },
          previewEditor(row){ //回馈预览
            this.isShowDia=true;
            this.$nextTick(()=>{
              this.$refs.HuikuiInfo.recallShow(row.id,row,3);
            })
          },
          async exportData(){ // 导出
            this.searchForm.pageNo=1;
            this.searchForm.pageSize=1000000000;
            if(this.selectKeys.length>0){
                let newData = JSON.parse(JSON.stringify(this.selectKeys));
                exportDataToExcel(newData,this.option.column,'TVM票款差异协查');
            }else {
              let res=await getTvmTicketCYXCList(this.searchForm);
              let data = res.data.data;
              exportDataToExcel(data,this.option.column,'TVM票款差异协查');
            }
          },
          delBatchs: function () {
            if (this.selectKeys.length<=0) {
              this.$message.error("请选择数据！");
              return false;
            }
            let ids = [];
            for(let i=0;i<this.selectKeys.length;i++){
              if (this.selectKeys[i].assistInvestStatus != "1" || this.selectKeys[i].kyAssistInvestStatus != "1") {
                this.$message.error("请检查数据，只能删除待下发的数据！");
                return false;
              }
              ids.push(this.selectKeys[i].id);
            }
            this.$confirm("确认删除?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              delBatch(ids)
                .then((data) => {
                  this.$message.success("删除成功");
                  this.getList(this.page);
                  done();
                })
                .catch(() => {
                  loading();
                });
            });
          },
          getOption(){
            let th=this;
            return  {
              emptyBtn:false,
              editBtn:false,
              delBtn:false,
              addBtn:false,
              border: true,
              index:true,
              indexLabel:'序号',
              align:'center',
              menuWidth:150,
              menuAlign:'center',
              selection: true,
              reserveSelection:false,
              height: 500,
              column:[
                {prop:'stationCode', width: 180, label:'站点',search:true,searchslot:true,formatter: function(row, value , label, column){
                    return getStationName(row.lineCode,value);
                  }},
              {prop:'settleTime', width: 120, label:'收入日期',search:true,searchslot:true,valueFormat:'yyyy-MM-dd'},
              {prop:'lineCode', width: 120, label:'线路',hide:true,type:'select',search:false,searchslot:true,formatter: function(row, value , label, column){
                  return getLineName(value);
                }},
              {prop:'tvmOrder',label:'TVM编号',search:true,searchslot:true},
              {prop:'systemMoney',label:'系统金额', formatter: function(row, value , label, column){
                return fenExYuangettoFixed2(value);
                }},
              // {prop:'tvmUnloadMoney',width: 120,label:'卸载显示金额',hide:true,formatter:function(row, value , label, column){
              //   var num =value / 100;
              //   num = num.toFixed(2);
              //   return num;
              //   }},
              {prop:'actualMoney',label:'实点金额',
                formatter:function(row, value , label, column){
                  // var num =value / 100;
                  // num = num.toFixed(2);
                  return fenExYuangettoFixed2(value+row.handOutMoney);
                }},
              // {prop:'handOutMoney',width: 120,label:'手工清出金额',hide:true,
              //   formatter:function(row, value , label, column){
              //     var num =value / 100;
              //     num = num.toFixed(2);
              //     return num;
              //   }
              // },
              {prop:'diffMoney',label:'差异金额',formatter:function(row, value , label, column){
                var num =value / 100;
                num = num.toFixed(2);
                return num;
                }},
               {prop:'boxCashType',width: 120,label:'钱箱类型',formatter :function(row, value , label, column){
                  return getQianxiangType(value);
                },},
              //  {prop:'diffReason',label:'钱箱编号',formatter :function(row, value , label, column){
              //     return row.cashBoxCode;
              //   }},
              // {prop:'diffReason',label:'差异原因',formatter :function(row, value , label, column){
              //     return row.diffReasonName;
              //   }},
              {prop:'jdReplyStatus',width: 120,label:'机电协查状态',search:true,searchLabelWidth:100,type:'select',
                dicData:[{
                  label: '未反馈',
                  value: 0
                },{
                  label: '已反馈',
                  value: 1
                }],
                formatter:function(row, value , label, column){
                  return value == 0?'未反馈':'已反馈';
                }
              },

              {label:"协查流程状态",width: 120,prop:"assistInvestStatus",type:'select',search:true,searchLabelWidth:100,
                dicData:xieChaStatus(),
                formatter: function(row, value , label, column){
                    return getXieChaStatusFormat(value);
                }},
	       {prop:'assistCategory',label:'协查类型',dicData:assistCategoryData(),type:'select',search:true,
                    formatter:function(row, value , label, column){
                      return getAssistCategory(value);
                    }},
              {prop:'replaceStatus',label:'替换状态',type:'select',search:true,dicData:repalceStatus(),
                formatter:function(row, value , label, column){
                  return getRepalceStatus(value);
                }},
              {prop:'sendPersonName',width:120,label:'下发人',}
            ]
            }
          },
          otherVueAction(){ //供其他Vue页面调用
            let th=this;
            transitUtil.$on('PK_call',(param)=>{
              getTvmTicketCYXCList({relationid:param.id}).then((response)=>{
                th.data = response.data.data;
                th.previewEditor(th.data[0]);
              });
            })
            transitUtil.$on('PK_view',(param)=>{
              this.searchForm.relationid = param.id;
              this.getList();
            });

          }
          },
      mounted() {
        getLineCodes().then(res=>{ //获取线路
          this.lineCodes=res;
        });
        this.otherVueAction();
      }
    }
</script>
<style lang="scss">

</style>
